package com.yanyi.music.controller;

import com.alibaba.fastjson.JSONObject;
import com.yanyi.music.domain.Singer;
import com.yanyi.music.service.impl.SingerServiceImpl;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
 * 歌手控制类
 */
@Api(tags = "歌手API")
@RestController
@RequestMapping("/singer")
public class SingerController {
    @Autowired
    private SingerServiceImpl singerService;

    @RequestMapping(value = "/selectByPrimaryKey", method = RequestMethod.GET)
    public Object findByKey(HttpServletRequest request) {
        return singerService.selectByPrimaryKey(Integer.valueOf(request.getParameter("id")));
    }

    @RequestMapping(value = "/allSinger", method = RequestMethod.GET)
    public Object allSinger() {
        return singerService.findAll(null);
    }

    @RequestMapping(value = "/singerOfName", method = RequestMethod.GET)
    public Object singerOfName(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        map.put("name", request.getParameter("name").trim());
        return singerService.findAll(map);
    }

    @RequestMapping(value = "/singerOfSex", method = RequestMethod.GET)
    public Object singerOfSex(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        map.put("sex", request.getParameter("sex").trim());
        return singerService.findAll(map);
    }

    @RequestMapping(value = "/delete", method = RequestMethod.DELETE)
    public Object delSinger(HttpServletRequest request) {
        return singerService.deleteByPrimaryKey(Integer.valueOf(request.getParameter("id")));
    }

    /**
     * 添加歌手
     *
     * @param request
     * @return
     */
    //TODO 使用DTO接收
    @ResponseBody
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Object addSinger(HttpServletRequest request) {
        JSONObject json = new JSONObject();
        String name = request.getParameter("name").trim();
        String sex = request.getParameter("sex").trim();
        String pic = request.getParameter("pic").trim();
        String birth = request.getParameter("birth").trim();
        String location = request.getParameter("location").trim();
        String introduction = request.getParameter("introduction").trim();
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date myBirth = new Date();
        try {
            myBirth = dateFormat.parse(birth);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Singer singer = new Singer();
        singer.setName(name);
        singer.setSex(new Byte(sex));
        singer.setPic(pic);
        singer.setBirth(myBirth);
        singer.setLocation(location);
        singer.setIntroduction(introduction);
        int res = singerService.insert(singer);
        if (res == 1) {
            json.put("code", 1);
            json.put("msg", "添加成功");
        } else {
            json.put("code", 0);
            json.put("msg", "添加失败");
        }
        return json;
    }

    /**
     * 更新歌手信息
     *
     * @param request
     * @return
     */
    //TODO 使用DTO接收
    @ResponseBody
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public Object editSinger(HttpServletRequest request) {
        JSONObject json = new JSONObject();
        String id = request.getParameter("id").trim();
        String name = request.getParameter("name").trim();
        String sex = request.getParameter("sex").trim();
        String birth = request.getParameter("birth").trim();
        String location = request.getParameter("location").trim();
        String introduction = request.getParameter("introduction").trim();
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date myBirth = new Date();
        try {
            myBirth = dateFormat.parse(birth);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Singer singer = new Singer();
        singer.setId(Integer.valueOf(id));
        singer.setName(name);
        singer.setSex(new Byte(sex));
        singer.setBirth(myBirth);
        singer.setLocation(location);
        singer.setIntroduction(introduction);
        int res = singerService.updateByPrimaryKeySelective(singer);
        if (res == 1) {
            json.put("code", 1);
            json.put("msg", "修改成功");
        } else {
            json.put("code", 0);
            json.put("msg", "修改失败");
        }
        return json;
    }

    @ResponseBody
    @RequestMapping(value = "/updateSingerPic", method = RequestMethod.POST)
    public Object updateSingerPic(@RequestParam("file") MultipartFile avatarFile, @RequestParam("id") int id) {
        JSONObject json = new JSONObject();
        if (avatarFile.isEmpty()) {
            json.put("code", 0);
            json.put("msg", "文件上传失败");
            return json;
        }
        //文件新的名称
        String fileName = System.currentTimeMillis() + avatarFile.getOriginalFilename();
//        String fileName = System.currentTimeMillis()+avatarFile.getOriginalFilename().substring(avatarFile.getOriginalFilename().indexOf("."));
        //TODO 注意不同系统中文件路径不一样System.getProperty("file.separator")
        String filePath = System.getProperty("user.dir") + System.getProperty("file.separator") + "img" + System.getProperty("file.separator") + "singerPic";

        File file = new File(filePath);
        if (!file.exists()) {
            file.mkdirs();
        }
        File dest = new File(filePath + System.getProperty("file.separator") + fileName);
        String storeAvatarPath = "/img/singerPic/" + fileName;
        try {
            avatarFile.transferTo(dest);
            Singer singer = new Singer();
            singer.setId(id);
            singer.setPic(storeAvatarPath);
            int i = singerService.updateByPrimaryKeySelective(singer);
            if (i == 1) {
                json.put("code", 1);
                json.put("pic", storeAvatarPath);
                json.put("msg", "上传成功");
            } else {
                json.put("code", 0);
                json.put("msg", "上传失败");
            }
        } catch (IOException ioException) {
            json.put("code", 0);
            json.put("msg", "上传失败" + ioException.getMessage());
        } finally {
            return json;
        }
    }
}
